package com.hjx.system;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;

/**
 * 部分属性只读上下文
 * @param <K> 键类型
 * @param <V> 值类型
 */
public class PartReadOnlyContext<K, V> extends HashMap {

    private Map<K, V> unModifiableMap;
    private Map<K, V> modifiableMap;
    private boolean canModify;

    public PartReadOnlyContext() {
        unModifiableMap = new HashMap<K, V>(32);
        modifiableMap = new HashMap<K, V>(32);
        canModify = true;
    }

    @Override
    public V get(Object key) {
        if (unModifiableMap.get(key) != null) {
            return unModifiableMap.get((V)key);
        }
        return modifiableMap.get(key);
    }

    @Override
    public V put(Object key, Object value) {
        if(canModify) {
            if(value instanceof String) {
                return unModifiableMap.put((K)key, (V) StringUtils.trim((String) value));
            } else {
                return unModifiableMap.put((K)key, (V) value);
            }
        }
        if(unModifiableMap.get((K)key) != null) {
            throw new IllegalArgumentException("当前键[" + key + "] 为上下文中只读属性，不可修改");
        }
        return modifiableMap.put((K)key, (V)value);
    }

    @Override
    public int size() {
        return unModifiableMap.size() + modifiableMap.size();
    }

    /**
     * 锁定只读上下文使其不可被修改
     */
    public void lockUnModifiableMap() {
        unModifiableMap = Collections.unmodifiableMap(unModifiableMap);
        canModify = false;
    }

    public static void main(String[] args) {
    PartReadOnlyContext<String, Object> context = new PartReadOnlyContext<String, Object>();
        context.put("a",1);
        context.put("b",1);
        context.put("c",1);

        context.lockUnModifiableMap();

        context.put("c", 3);

    }
}